import Router from 'koa-router';
import jwt from 'jsonwebtoken';
import { Op } from 'sequelize';
import { User, Friendship, Call } from '../models/index.js';
import { authMiddleware } from '../middlewares/auth.js';
import { generateToken, verifyToken } from '../utils/jwt.js';
import { sendVerificationCode } from '../utils/email.js';
import { generateCode, saveCode, verifyCode, verificationCodes } from '../utils/verificationCode.js';
import Pinyin from 'chinese-to-pinyin';

const router = new Router({
  prefix: '/api/users'
});

// 移除声调标记的函数
const removeToneMarks = (str) => {
  return str.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
};

// 用户注册
router.post('/register', async (ctx) => {
  try {
    console.log('Request headers:', ctx.headers);
    console.log('Query params:', ctx.query);
    console.log('Request body:', ctx.request.body);
    
    // 优先使用请求体中的数据，如果没有则使用查询参数
    const bodyData = ctx.request.body || {};
    const queryData = ctx.query || {};
    
    const phone = bodyData.phone || queryData.phone;
    const password = bodyData.password || queryData.password;
    const nickname = bodyData.nickname || queryData.nickname;
    
    console.log('Final values:', { phone, password, nickname });

    if (!phone || !password || !nickname) {
      ctx.status = 400;
      ctx.message = '手机号、密码和昵称都是必需的';
      return;
    }

    // 验证手机号是否已存在
    const existingUser = await User.findOne({ where: { phone } });
    if (existingUser) {
      ctx.status = 400;
      ctx.message = '该手机号已被注册';
      return;
    }

    // 创建新用户
    const user = await User.create({
      phone,
      password,  // 密码会在模型中自动加密
      nickname,
      status: 'offline'
    });

    // 生成二维码
    const qrCode = await user.generateQRCode();
    await user.update({ qrCode });

    ctx.status = 201;
    ctx.body = {
      id: user.id,
      phone: user.phone,
      nickname: user.nickname,
      avatar: user.avatar,
      qrCode: user.qrCode
    };

  } catch (error) {
    ctx.status = 500;
    ctx.message = error.message;

  }
});

// 密码登录
router.post('/login', async (ctx) => {
  try {
    const { email, password } = ctx.request.body;
    console.log('Login attempt:', { email });

    // 验证邮箱格式
    if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      ctx.throw(400, '请输入有效的邮箱地址');
    }

    // 验证密码是否提供
    if (!password) {
      ctx.throw(400, '请输入密码');
    }

    // 查找用户
    const user = await User.findOne({ where: { email } });
    if (!user) {
      ctx.throw(401, '用户不存在');
    }

    // 验证密码
    const isValidPassword = await user.validatePassword(password);
    if (!isValidPassword) {
      ctx.throw(401, '邮箱或密码错误');
    }

    // 更新最后登录时间和状态
    await user.update({
      lastLoginAt: new Date(),
      status: 'online'
    });

    // 生成 JWT token
    const token = generateToken({
      id: user.id,
      email: user.email,
      username: user.nickname
    });

    ctx.body = {
      token,
      user: {
        id: user.id,
        email: user.email,
        nickname: user.nickname,
        avatar: user.avatar,
        phone: user.phone,
        status: user.status
      }
    };
  } catch (error) {
    console.error('密码登录失败:', error);
    ctx.throw(500, error.message || '登录失败');
  }
});

// 邮箱验证码注册
router.post('/register/email', async (ctx) => {
  try {
    const { email, code, password, nickname } = ctx.request.body;
    console.log('Register attempt:', { email, code });

    // 验证邮箱格式
    if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      ctx.throw(400, '请输入有效的邮箱地址');
    }

    // 验证验证码
    if (!code || !verifyCode(email, code)) {
      ctx.throw(400, '验证码无效或已过期');
    }

    // 验证密码格式
    if (!password || password.length < 6 || password.length > 20) {
      ctx.throw(400, '密码长度必须在6-20位之间');
    }

    // 检查邮箱是否已被注册
    const existingUser = await User.findOne({ where: { email } });
    if (existingUser) {
      ctx.throw(400, '该邮箱已被注册');
    }

    // 创建新用户
    const user = await User.create({
      email,
      password,
      nickname: nickname || `用户${Math.random().toString(36).slice(2, 8)}`,
      status: 'online'
    });

    // 生成 JWT token
    const token = generateToken({
      id: user.id,
      email: user.email,
      username: user.nickname
    });

    ctx.body = {
      token,
      user: {
        id: user.id,
        email: user.email,
        nickname: user.nickname,
        avatar: user.avatar,
        phone: user.phone,
        status: user.status,
        isNewUser: true
      }
    };
  } catch (error) {
    console.error('邮箱注册失败:', error);
    ctx.throw(500, error.message || '注册失败');
  }
});

// 获取用户信息
router.get('/profile', authMiddleware, async (ctx) => {
  try {
    console.log('Request headers:', ctx.headers);
    console.log('Request query:', ctx.query);
    console.log('Request params:', ctx.params);
    
    const user = ctx.state.user;
    ctx.body = {
      id: user.id,
      phone: user.phone,
      nickname: user.nickname,
      avatar: user.avatar,
      status: user.status,
      qrCode: user.qrCode,
      lastLoginAt: user.lastLoginAt
    };
  } catch (error) {
    ctx.status = 500;
    ctx.message = error.message;
  }
});

// 更新用户信息
router.put('/profile', authMiddleware, async (ctx) => {
  try {

    
    const user = ctx.state.user;
    const { nickname, avatar } = ctx.request.body;
  
    await user.update({
      ...(nickname && { nickname }),
      ...(avatar && { avatar })
    });

    ctx.body = {
      id: user.id,
      phone: user.phone,
      nickname: user.nickname,
      avatar: user.avatar,
      status: user.status
    };

  } catch (error) {
    ctx.status = 500;
    const message = error.message.includes('昵称长度必须在2-20位之间') ? '昵称长度必须在2-20位之间' : error.message
    ctx.body = {
      code: 500,
      status: 500,
      message: message
    };
  }
});

// 查询是否真实用户(通过手机号)
router.get('/isRealUser', authMiddleware, async (ctx) => {
  try {
    const { phone } = ctx.query;
    if (!phone) {
      ctx.body = {
        code: 400,
        message: '手机号不能为空'
      };
      return;
    }

    // 通过手机号查询用户信息
    const user = await User.findOne({
      where: { phone },
      attributes: ['nickname', 'avatar', 'phone']
    });

    if (!user) {
      ctx.body = {
        code: 200,
        data: 'noUser'
      };
      return;
    }

    ctx.body = {
      code: 200,
      data: {
        nickname: user.nickname,
        avatar: user.avatar,
        phone: user.phone
      }
    };
  } catch (error) {
    console.error('查询用户信息失败:', error);
    ctx.body = {
      code: 500,
      message: '查询用户信息失败'
    };
  }
});

// 发送好友请求（通过手机号）
router.post('/friend/request', authMiddleware, async (ctx) => {
  try {
    console.log('Request headers:', ctx.headers);
    console.log('Request body:', ctx.request.body);
    console.log('Raw request body:', ctx.request.rawBody);
    
    const { friendPhone } = ctx.request.body;
    const user = ctx.state.user;

    // 验证参数
    if (!friendPhone) {
      ctx.status = 400;
      ctx.message = '好友手机号不能为空';
      return;
    }

    // 查找好友
    const friend = await User.findOne({ where: { phone: friendPhone } });

    // 检查好友是否存在
    if (!friend) {
      ctx.status = 404;
      ctx.body = {
        code: 404,
        error: '该手机号未注册'
      }
      return;
    }

    // 检查是否是自己
    if (user.id === friend.id) {
      ctx.status = 400;
      ctx.body = {
        code: 400,
        error: '不能添加自己为好友'
      }
      return;
    }

    // 检查是否已经是好友或有待处理的请求
    const existingFriendship = await Friendship.findOne({
      where: {
        [Op.or]: [
          { userId: user.id, friendId: friend.id },
          { userId: friend.id, friendId: user.id }
        ],
        status: {
          [Op.in]: ['accepted', 'pending']
        }
      }
    });

    if (existingFriendship) {
      if (existingFriendship.status === 'accepted') {
        ctx.status = 400;
        ctx.body = {
          code: 400,
          error: '已经是好友关系'
        }
        return;
      }
      
      if (existingFriendship.status === 'pending') {
        // 如果是对方发送的请求
        if (existingFriendship.userId === friend.id) {
          ctx.status = 400;
          ctx.body = {
            code: 400,
            error: '对方已经发送了好友请求给您，请直接处理该请求'
          }
          return;
        }
        // 如果是自己发送的请求
        ctx.status = 400;
        ctx.body = {
          code: 400,
          error: '好友请求已发送，等待对方确认'
        }
        return;
      }
    }

    // 如果有被拒绝的记录，删除它
    await Friendship.destroy({
      where: {
        [Op.or]: [
          { userId: user.id, friendId: friend.id },
          { userId: friend.id, friendId: user.id }
        ],
        status: 'rejected'
      }
    });

    // 创建新的好友请求
    const newFriendship = await Friendship.create({
      userId: user.id,
      friendId: friend.id,
      status: 'pending'
    });

    ctx.status = 201;
    ctx.body = {
      friendship: {
        id: newFriendship.id,
        status: newFriendship.status,
        friend: {
          id: friend.id,
          nickname: friend.nickname,
          phone: friend.phone,
          avatar: friend.avatar
        }
      }
    };

  } catch (error) {
    console.error('查询用户信息失败:', error);
    
    ctx.status = 500;
    ctx.body = {
      code: 500,
      error: error.message
    };

  }
});

// 查询是否真实用户(通过邮箱)
router.get('/isRealUser/email', authMiddleware, async (ctx) => {
  try {
    const { email } = ctx.query;
    if (!email) {
      ctx.body = {
        code: 400,
        message: '邮箱不能为空'
      };
      return;
    }

    // 通过邮箱查询用户信息
    const user = await User.findOne({
      where: { email },
      attributes: ['nickname', 'avatar', 'email']
    });

    if (!user) {
      ctx.body = {
        code: 200,
        data: 'noUser'
      };
      return;
    }

    ctx.body = {
      code: 200,
      data: {
        nickname: user.nickname,
        avatar: user.avatar,
        email: user.email
      }
    };
  } catch (error) {
    console.error('查询用户信息失败:', error);
    ctx.body = {
      code: 500,
      message: '查询用户信息失败'
    };
  }
});

// 发送好友请求（通过邮箱）
router.post('/friend/email/request', authMiddleware, async (ctx) => {
  try {
    const { friendEmail } = ctx.request.body;
    const user = ctx.state.user;

    // 验证参数
    if (!friendEmail) {
      ctx.status = 400;
      ctx.message = '好友邮箱不能为空';
      return;
    }

    // 查找好友
    const friend = await User.findOne({ where: { email: friendEmail } });

    // 检查好友是否存在
    if (!friend) {
      ctx.status = 404;
      ctx.body = {
        code: 404,
        error: '该邮箱未注册'
      }
      return;
    }

    // 检查是否是自己
    if (user.id === friend.id) {
      ctx.status = 400;
      ctx.body = {
        code: 400,
        error: '不能添加自己为好友'
      }
      return;
    }

    // 检查是否已经是好友或有待处理的请求
    const existingFriendship = await Friendship.findOne({
      where: {
        [Op.or]: [
          { userId: user.id, friendId: friend.id },
          { userId: friend.id, friendId: user.id }
        ],
        status: {
          [Op.in]: ['accepted', 'pending']
        }
      }
    });

    if (existingFriendship) {
      if (existingFriendship.status === 'accepted') {
        ctx.status = 400;
        ctx.body = {
          code: 400,
          error: '已经是好友关系'
        }
        return;
      }
      
      if (existingFriendship.status === 'pending') {
        // 如果是对方发送的请求
        if (existingFriendship.userId === friend.id) {
          ctx.status = 400;
          ctx.body = {
            code: 400,
            error: '对方已经发送了好友请求给您，请直接处理该请求'
          }
          return;
        }
        // 如果是自己发送的请求
        ctx.status = 400;
        ctx.body = {
          code: 400,
          error: '好友请求已发送，等待对方确认'
        }
        return;
      }
    }

    // 如果有被拒绝的记录，删除它
    await Friendship.destroy({
      where: {
        [Op.or]: [
          { userId: user.id, friendId: friend.id },
          { userId: friend.id, friendId: user.id }
        ],
        status: 'rejected'
      }
    });

    // 创建新的好友请求
    const newFriendship = await Friendship.create({
      userId: user.id,
      friendId: friend.id,
      status: 'pending'
    });

    ctx.status = 201;
    ctx.body = {
      friendship: {
        id: newFriendship.id,
        status: newFriendship.status,
        friend: {
          id: friend.id,
          nickname: friend.nickname,
          email: friend.email,
          avatar: friend.avatar
        }
      }
    };

  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      code: 500,
      error: error.message
    };

  }
});

// 获取好友请求列表
router.get('/friend/requests', authMiddleware, async (ctx) => {
  try {
    console.log('Request headers:', ctx.headers);
    console.log('Request query:', ctx.query);
    console.log('Request params:', ctx.params);
    
    const { type = 'received' } = ctx.query;
    const user = ctx.state.user;

    const where = {
      status: 'pending',
      ...(type === 'received' 
        ? { friendId: user.id }
        : { userId: user.id })
    };

    const requests = await Friendship.findAll({
      where,
      include: [
        {
          model: User,
          as: type === 'received' ? 'user' : 'friend',
          attributes: ['id', 'phone', 'nickname', 'avatar', 'status']
        }
      ],
      order: [['createdAt', 'DESC']]
    });

    const formattedRequests = requests.map(request => ({
      id: request.id,
      status: request.status,
      createdAt: request.createdAt,
      [type === 'received' ? 'sender' : 'receiver']: {
        id: request[type === 'received' ? 'user' : 'friend'].id,
        phone: request[type === 'received' ? 'user' : 'friend'].phone,
        nickname: request[type === 'received' ? 'user' : 'friend'].nickname,
        avatar: request[type === 'received' ? 'user' : 'friend'].avatar,
        status: request[type === 'received' ? 'user' : 'friend'].status
      }
    }));

    ctx.body = {
      total: formattedRequests.length,
      requests: formattedRequests
    };
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      code: 500,
      error: error.message
    }

  }
});

// 处理好友请求
router.put('/friend/request/:requestId', authMiddleware, async (ctx) => {
  try {
    console.log('Request headers:', ctx.headers);
    console.log('Request body:', ctx.request.body);
    console.log('Raw request body:', ctx.request.rawBody);
    
    const { requestId } = ctx.params;
    const { action } = ctx.request.body;
    const user = ctx.state.user;

    if (!['accept', 'reject'].includes(action)) {
      ctx.status = 400;
      ctx.message = '无效的操作';
      return;
    }

    const friendship = await Friendship.findOne({
      where: {
        id: requestId,
        friendId: user.id,
        status: 'pending'
      },
      include: [
        {
          model: User,
          as: 'user',
          attributes: ['id', 'phone', 'nickname', 'avatar', 'status']
        }
      ]
    });

    if (!friendship) {
      ctx.status = 404;
      ctx.body = {
        code: 404,
        error: '好友请求不存在或已处理'
      };

      return;
    }

    if (action === 'accept') {
      await friendship.update({
        status: 'accepted'
      });
      
      ctx.body = {
        friendship: {
          id: friendship.id,
          status: 'accepted',
          friend: {
            id: friendship.user.id,
            phone: friendship.user.phone,
            nickname: friendship.user.nickname,
            avatar: friendship.user.avatar,
            status: friendship.user.status
          }
        }
      };
    } else {
      await friendship.update({
        status: 'rejected'
      });
      
      ctx.body = {
        friendship: {
          id: friendship.id,
          status: 'rejected',
          friend: {
            id: friendship.user.id,
            phone: friendship.user.phone,
            nickname: friendship.user.nickname,
            avatar: friendship.user.avatar,
            status: friendship.user.status
          }
        }
      };
    }

  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      code: 500,
      error: error.message
    };

  }
});

// 获取好友列表
router.get('/friends', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user;

    const friendships = await Friendship.findAll({
      where: {
        [Op.or]: [
          { userId: user.id, status: 'accepted' },
          { friendId: user.id, status: 'accepted' }
        ]
      },
      include: [
        {
          model: User,
          as: 'user',
          attributes: ['id', 'nickname', 'phone', 'avatar', 'status', 'email']
        },
        {
          model: User,
          as: 'friend',
          attributes: ['id', 'nickname', 'phone', 'avatar', 'status', 'email']
        }
      ]
    });

    const friends = friendships.map(friendship => {
      const friend = friendship.userId === user.id ? friendship.friend : friendship.user;
      
      // 获取昵称的拼音首字母
      let pinyinFirst = '#';
      try {
        if (friend.nickname) {
          // 如果第一个字符是字母，直接使用
          if (/^[a-zA-Z]/.test(friend.nickname)) {
            pinyinFirst = friend.nickname.charAt(0).toUpperCase();
          } else {
            // 获取完整拼音并移除声调
            const pinyinStr = Pinyin(friend.nickname, {
              removeSpace: true,
              toneType: 'none'
            });
            // 移除声调标记并取第一个字母
            pinyinFirst = removeToneMarks(pinyinStr.charAt(0)).toUpperCase();
          }
        }
      } catch (error) {
        console.error('获取拼音失败:', error);
      }

      return {
        id: friend.id,
        nickname: friend.nickname,
        phone: friend.phone,
        avatar: friend.avatar,
        email: friend.email,
        status: friend.status,
        friendshipId: friendship.id,
        pinyinFirst
      };
    });

    // 按拼音首字母排序
    friends.sort((a, b) => {
      return a.pinyinFirst.localeCompare(b.pinyinFirst);
    });

    ctx.body = { friends };
  } catch (error) {
    console.log(error);
    
    ctx.status = 500;
    ctx.body = {
      code: 500,
      error: error.message
    };
  }
});

// 获取通话记录列表
router.get('/calls', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user;
    const { type = 'all', status, page = 1, pageSize = 20 } = ctx.query;
    
    const where = {};
    if (status) {
      where.status = status;
    }

    // 构建查询条件
    const query = {
      where,
      include: [
        {
          model: User,
          as: 'caller',
          attributes: ['id', 'nickname', 'avatar', 'phone', 'email']
        },
        {
          model: User,
          as: 'receiver',
          attributes: ['id', 'nickname', 'avatar', 'phone', 'email']
        }
      ],
      order: [['createdAt', 'DESC']],
      offset: (page - 1) * pageSize,
      limit: parseInt(pageSize)
    };

    let calls;
    let total;

    // 根据类型筛选通话记录
    if (type === 'outgoing') {
      where.callerId = user.id;
      calls = await Call.findAll(query);
      total = await Call.count({ where });
    } else if (type === 'incoming') {
      where.receiverId = user.id;
      calls = await Call.findAll(query);
      total = await Call.count({ where });
    } else {
      // 查询所有相关通话记录
      where[Op.or] = [
        { callerId: user.id },
        { receiverId: user.id }
      ];
      calls = await Call.findAll(query);
      total = await Call.count({ where });
    }

    // 格式化返回数据
    const formattedCalls = calls.map(call => {
      const isOutgoing = call.callerId === user.id;
      return {
        id: call.id,
        callId: call.callId,
        status: call.status,
        startTime: call.startTime,
        endTime: call.endTime,
        duration: call.duration,
        callType: call.callType,
        direction: isOutgoing ? 'outgoing' : 'incoming',
        otherParty: isOutgoing ? call.receiver : call.caller
      };
    });

    ctx.body = {
      code: 200,
      data: {
        total,
        page: parseInt(page),
        pageSize: parseInt(pageSize),
        list: formattedCalls
      }
    };
  } catch (error) {
    console.error('获取通话记录失败:', error);
    ctx.status = 500;
    ctx.body = {
      code: 500,
      error: '获取通话记录失败'
    };
  }
});

// 获取指定用户的通话记录
router.get('/calls/:userId', authMiddleware, async (ctx) => {
  try {
    const { userId } = ctx.params;
    const { type = 'all', status, page = 1, pageSize = 20 } = ctx.query;

    const where = { [Op.or]: [{ callerId: userId }, { receiverId: userId }] };
    if (status) {
      where.status = status;
    }

    const query = {
      where,
      include: [
        {
          model: User,
          as: 'caller',
          attributes: ['id', 'nickname', 'avatar', 'phone', 'email']
        },
        {
          model: User,
          as: 'receiver',
          attributes: ['id', 'nickname', 'avatar', 'phone', 'email']
        }
      ],
      order: [['createdAt', 'DESC']],
      offset: (page - 1) * pageSize,
      limit: parseInt(pageSize)
    };

    const calls = await Call.findAll(query);
    const total = await Call.count({ where });

    const formattedCalls = calls.map(call => {
      const isOutgoing = call.callerId === userId;
      return {
        id: call.id,
        callId: call.callId,
        status: call.status,
        startTime: call.startTime,
        endTime: call.endTime,
        duration: call.duration,
        callType: call.callType,
        direction: isOutgoing ? 'outgoing' : 'incoming',
        otherParty: isOutgoing ? call.receiver : call.caller
      };
    });

    ctx.body = {
      code: 200,
      data: {
        total,
        page: parseInt(page),
        pageSize: parseInt(pageSize),
        list: formattedCalls
      }
    };
  } catch (error) {
    console.error('获取通话记录失败:', error);
    ctx.status = 500;
    ctx.body = {
      code: 500,
      error: '获取通话记录失败'
    };
  }
});

// 获取通话详情
router.get('/calls/:callId', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user;
    const { callId } = ctx.params;

    const call = await Call.findOne({
      where: {
        callId,
        [Op.or]: [
          { callerId: user.id },
          { receiverId: user.id }
        ]
      },
      include: [
        {
          model: User,
          as: 'caller',
          attributes: ['id', 'nickname', 'avatar', 'phone']
        },
        {
          model: User,
          as: 'receiver',
          attributes: ['id', 'nickname', 'avatar', 'phone']
        }
      ]
    });

    if (!call) {
      ctx.status = 404;
      ctx.body = {
        code: 404,
        error: '通话记录不存在'
      };
      return;
    }

    const isOutgoing = call.callerId === user.id;
    ctx.body = {
      code: 200,
      data: {
        id: call.id,
        callId: call.callId,
        status: call.status,
        startTime: call.startTime,
        endTime: call.endTime,
        duration: call.duration,
        callType: call.callType,
        direction: isOutgoing ? 'outgoing' : 'incoming',
        otherParty: isOutgoing ? call.receiver : call.caller
      }
    };
  } catch (error) {
    console.error('获取通话详情失败:', error);
    ctx.status = 500;
    ctx.body = {
      code: 500,
      error: '获取通话详情失败'
    };
  }
});

// 查询全部app用户
router.get('/users', async (ctx) => {
  try {
    const {
      page = 1,
      pageSize = 10,
      nickname = '',
      phone = '',
      email = '',
      status,
      sortBy = 'createdAt',
      sortOrder = 'DESC'
    } = ctx.query;

    // 构建查询条件
    const where = {};
    if (nickname) {
      where.nickname = { [Op.like]: `%${nickname}%` };
    }
    if (email) {
      where.email = { [Op.like]: `%${email}%` };
    }
    if (status) {
      where.status = status;
    }

    // 执行查询
    const { count, rows } = await User.findAndCountAll({
      where,
      attributes: [
        'id', 'phone', 'email' ,'nickname', 'avatar', 'status',
        'lastLoginAt', 'qrCode', 'createdAt', 'updatedAt'
      ],
      order: [[sortBy, sortOrder]],
      limit: parseInt(pageSize),
      offset: (parseInt(page) - 1) * parseInt(pageSize)
    });

    // 返回结果
    ctx.body = {
      total: count,
      totalPages: Math.ceil(count / pageSize),
      currentPage: parseInt(page),
      pageSize: parseInt(pageSize),
      list: rows
    };
  } catch (error) {
    console.error('查询用户列表失败:', error);
    ctx.throw(500, '查询用户列表失败');
  }
});

// 发送邮箱验证码
router.post('/send-code', async (ctx) => {
  try {
    const { email } = ctx.request.body;
    console.log('Sending code to email:', email);

    // 验证邮箱格式
    if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      ctx.throw(400, '请输入有效的邮箱地址');
    }

    // 生成验证码
    const code = generateCode(6);
    console.log('Generated code:', code);
    
    // 发送验证码邮件
    const sent = await sendVerificationCode(email, code);
    console.log('Email send result:', sent);
    
    if (!sent) {
      ctx.throw(500, '验证码发送失败');
    }

    // 保存验证码（5分钟有效期）
    saveCode(email, code, 5 * 60 * 1000);
    console.log('Code saved for email:', email);
    
    // 验证是否保存成功
    const stored = verificationCodes[email];
    console.log('Verification after save:', stored);

    ctx.body = {
      message: '验证码已发送，请检查邮箱'
    };
  } catch (error) {
    console.error('发送验证码失败:', error);
    ctx.throw(500, error.message || '发送验证码失败');
  }
});

export default router;
